package io.github.bomb.batch.rest;


import io.github.bomb.batch.application.BatchTaskService;
import io.github.bomb.batch.application.TaskExecutionService;
import io.github.bomb.batch.domain.BatchTask;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.List;

/**
 * BatchTaskController
 * 提供批处理任务的 API。
 */
@RestController
public class BatchTaskController {

	private final BatchTaskService batchTaskService;
	private final TaskExecutionService taskExecutionService;

	public BatchTaskController(BatchTaskService batchTaskService,
							   TaskExecutionService taskExecutionService) {
		this.batchTaskService = batchTaskService;
		this.taskExecutionService = taskExecutionService;
	}

	@GetMapping("/tasks")
	public List<BatchTask> getAllTasks() {
		return batchTaskService.getAllTasks();
	}

	@PostMapping("/run-task/{taskId}")
	public String runTask(@PathVariable Long taskId) {
		try {
			BatchTask task = batchTaskService.getAllTasks().stream()
					.filter(t -> t.getId().equals(taskId))
					.findFirst()
					.orElseThrow(() -> new IllegalArgumentException("Task not found"));
			taskExecutionService.executeTask(task);
			return "Task executed successfully!";
		} catch (Exception e) {
			return "Task execution failed: " + e.getMessage();
		}
	}
}
